package com.agil.photoalbum.db.dao;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Query;
import org.hibernate.Session;

import com.agil.photoalbum.db.util.SessionManager;

public class HibernateBaseDAO {
	
	private static final Log log = LogFactory.getLog(HibernateBaseDAO.class);
	
	public <E> boolean save(E transientInstance) {		
		Session hbSession = SessionManager.getCurrentSession();
		log.info("saving " + transientInstance.getClass() + " instance");
		try {			
			hbSession.save(transientInstance);
			SessionManager.commitTransaction();
			log.info("save successful");
			return true;
		} catch (RuntimeException re) {	
			SessionManager.rollbackTransaction();
			log.info("save failed", re);
			return false;

		} 
	}

	public <E> boolean delete(E persistentInstance) {
		Session hbSession = SessionManager.getCurrentSession();
		log.info("deleting " + persistentInstance.getClass() + " instance");
		try {
			hbSession.delete(persistentInstance);
			SessionManager.commitTransaction();
			log.info("delete successful");
			return true;
		} catch (RuntimeException re) {
			SessionManager.rollbackTransaction();
			log.info("delete failed", re);
			return false;
//			throw re;
		} finally {
			//SessionManager.closeSession();
		}
	}
	
	public <E> void attachDirty(E instance) {
		Session hbSession = SessionManager.getCurrentSession();
		log.info("attaching dirty " + instance.getClass() + " instance");
		try {
			hbSession.saveOrUpdate(instance);
			SessionManager.commitTransaction();
			log.info("attach successful");
		} catch (RuntimeException re) {
			SessionManager.rollbackTransaction();
			log.info("attach failed", re);
			throw re;
		} 
	}
	
	@SuppressWarnings("unchecked")
	public <E> E findById(Class<E> e,java.lang.Long id) {
		Session hbSession = SessionManager.getCurrentSession();
		log.info("getting "+e.getClass()+" instance with id: " + id);
		try {			
			E instance = (E) hbSession.get(e.getName(), id);			
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		} 
	}
	
	@SuppressWarnings("unchecked")
	public <E> List<E> findAll(Class<E> e) {
		Session hbSession = SessionManager.getCurrentSession();
		log.info("finding all " + e.getName() + " instances");
		try {
			String queryString = "from "+e.getName();
			
			Query queryObject = hbSession.createQuery(queryString);			
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		} 
	}

}
